var fs = require('fs'),
    path = require('path');

var ROOT = path.resolve(__dirname, '../traces/origin_traces/'),
    protoMap = {
        'SMTP': 1,
        'HTTP': 1,
        'FTP': 0,
        'DNS': 0
    };

function getRandomFromRange(start, stop) {
   return Math.floor(Math.random() * (stop-start) + start); 
}

function calculateStopTime(startTime, simuTime, trace) {

    var content = fs.readFileSync(trace, 'utf-8').split('\n'),
        stopTime = startTime;
    
    for (var i = 0, len = content.length; i < len; i++) {
        if (content[i].length > 2) {
            var arr = content[i].split(' ');            
            time = parseFloat(arr[2]);
            if (startTime + time <= simuTime) {
                stopTime = startTime + time;
            }
        }
    }

    return stopTime;
}

function getReverseTrace(trace) {
  // src-dst.txt
  return trace.slice(0, trace.length-4).split('-').reverse().join('-') + '.txt';
}

function generateFlowDescription(simuTime, flow) {

    // UNIT: us
    simuTime *= 1000000;
    
    var root = path.resolve(ROOT, flow.proto),
        traces = fs.readdirSync(root),
        content = '',
        dstPort,
        traceIndex,
        trace,
        tos,
        startTime,
        stopTime,
        server = [],
        reverseTrace = '',
        i = 0,
        len = flow.num;

    while (i < len) {
        dstPort = getRandomFromRange(10, 100); 
        traceIndex = getRandomFromRange(0, traces.length);
        trace = path.resolve(root, traces[traceIndex]);
        tos = getRandomFromRange(0, 3);
        startTime = getRandomFromRange(0, simuTime); 
        stopTime = calculateStopTime(startTime, simuTime, trace);

        server.push([flow.dst, dstPort, protoMap[flow.proto]].join('-'));
        content += [flow.src, flow.dst, dstPort, trace, tos, startTime / 1000000, stopTime / 1000000, protoMap[flow.proto], '\n'].join(' ');
        i++;

        reverseTrace = path.resolve(root, getReverseTrace(traces[traceIndex]));
        if (fs.existsSync(reverseTrace)) {
            tos = getRandomFromRange(0, 3);
            startTime = getRandomFromRange(0, simuTime); 
            stopTime = calculateStopTime(startTime, simuTime, trace);

            server.push([flow.dst, dstPort, protoMap[flow.proto]].join('-'));
            content += [flow.src, flow.dst, dstPort, reverseTrace, tos, startTime / 1000000, stopTime / 1000000, protoMap[flow.proto], '\n'].join(' ');
            i++;
        }
    }

    console.log('[SIMULATION] content from real trace are\n', content);

    return {
        content: content,
        server: server
    };
}

exports.generateFlowDescription = generateFlowDescription;
